import request from '@/config/request'
import { getAnswerScoreable, jywConvertToXkw } from '@/utils/question'
import { getAllSubjectApi, getSelfModuleSubjectApi, questionSplitApi } from '@/api/common'

// 进入/退出错题本
export const wrongBookRecordApi = (data) => {
  return request.post('/app-api/question/wrong-question-book/wrongBookRecord', data)
}

// 获取科目
export const getSubjectApi = () => {
  return new Promise((resolve) => {
    Promise.all([
      getAllSubjectApi({
        formatter: (subjects) => {
          return subjects.map((item) => {
            return {
              subjectId: item.value,
              subjectName: item.label
            }
          })
        }
      }),
      getSelfModuleSubjectApi()
    ]).then((res) => {
      const [subjectIdListData, moduleSubjectListData] = res
      const { data: subjectIdList } = subjectIdListData
      const { data: moduleSubjectList } = moduleSubjectListData

      // 获取已经开通的科目
      if (Array.isArray(moduleSubjectList) && moduleSubjectList.length > 0) {
        const selfSubjectList = moduleSubjectList.filter((i) => i.moduleId === '2')
        if (Array.isArray(subjectIdList) && selfSubjectList.length > 0) {
          const copySubjectIdList = JSON.parse(JSON.stringify(subjectIdList))
          const selfSubjectIds = selfSubjectList.map((i) => i.subject)
          subjectIdList.splice(0, subjectIdList.length)
          subjectIdList.push(
            ...copySubjectIdList.filter((i) => selfSubjectIds.includes(i.subjectId))
          )
        } else {
          subjectIdList.splice(0, subjectIdList.length)
        }
      } else {
        subjectIdList.splice(0, subjectIdList.length)
      }

      resolve(subjectIdListData)
    })
  })
}

// 获取知识点
export const getKpointApi = (data) => {
  return request.get('/app-api/question/wrong-question-book/getKpoint', data)
}

// 获取题型
export const getQuestionTypeApi = (data) => {
  return request.get(`/app-api/question/wrong-question-book/getType`, data)
}

// 获得错题本分页
export const getWrongQuestionBookPageApi = (data) => {
  return new Promise(async (resovle) => {
    const res = await request.get('/app-api/question/wrong-question-book/page', data)

    try {
      if (res.data) {
        // 获取题目详情
        const { data: questions } = await getListCompleteByIdsApi({
          ids: res.data.list.map((q) => q.questionId).join(',')
        })

        // 解析题目
        res.data.list = res.data.list.map((q) => {
          // 如果不是学科网题目，将题目改为学科网的题目结构
          if (q.sourceType && q.sourceType === '3') {
            const { questionId, typeName, stem, options } = q

            if (['选择题', '多选题'].includes(typeName)) {
              // 选择题
              // 题干
              let stemHtml = ''
              const stemOptions = JSON.parse(options)
              let stemOptionsHtml = ''
              if (Array.isArray(stemOptions)) {
                stemOptions.forEach((option, index) => {
                  stemOptionsHtml += `<td>${'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.charAt(
                    index
                  )}.&nbsp;<span class=\"qml-op\"><span>${option}</span></span></td>`
                })
              }

              if (stem.indexOf('MathJye') != -1) {
                stemHtml = `<p></p><fieldset style="margin-top:0.1rem;font-size:0.26rem">${stem}</fieldset>`
              } else {
                stemHtml = `<p>${stem}</p>`
              }
              q.stem = `<div class=\"qml-stem\">${stemHtml}<div class=\"qml-og\"><table style=\"width:100%\"class=\"qml-og\"><tbody><tr>${stemOptionsHtml}</tr></tbody></table></div></div>`
            }

            // 解析
            const questionSource = questions.find((q) => questionId.indexOf(q.questionId) != -1)
            const { explanation, method, discuss } = questionSource
            const content = `<div class=\"qml-seg\" seg-name=\"详解\">【分析】<div style=\"\">${
              explanation ? explanation : '无'
            }</div></div>`
            q.method = `<div class=\"qml-seg\" seg-name=\"解答\">【解答】<div style=\"\">${
              method ? method : '无'
            }</div></div>`
            q.discuss = `<div class=\"qml-seg\" seg-name=\"点评\">【点评】<div style=\"\">${
              discuss ? discuss : '无'
            }</div></div>`
            q.explanation = `<div class=\"qml-explanation\">${content}${q.method}${q.discuss}</div>`
          }

          return q
        })
      }
    } catch (error) {
      console.error(error)
    }

    resovle(res)
  })
}

// 拍照搜题
export const searchQuestionsByImageApi = (data) => {
  return request.post('/app-api/question/app/question/textSearch', data)
}

// 更新搜题时间
export const updateSearchQuestionsTime = (data) => {
  return request.post('/app-api/question/app/question/updateTextSearchTime', data)
}

// 学科网知识点标注
export const kpointPredictApi = (data) => {
  return request.post('/app-api/question/student-question/kpointPredict', data)
}

// 获取题型(拍照上传错题)
export const getStudentQuestionTypeApi = (data) => {
  return request.get(`/app-api/question/student-question/getType`, data)
}

// 获取知识点树(拍照上传错题)
export const getStudentQuestionKpointTreeApi = (data) => {
  return request.get(`/app-api/question/student-question/getKpointTree`, data)
}

// 创建拍照上传错题
export const createStudentQuestionApi = (data) => {
  return request.post('/app-api/question/student-question/create', data)
}

// 删除拍照上传错题
export const deleteStudentQuestion = (id) => {
  return request.delete(`/app-api/question/student-question/delete?id=${id}`)
}

// 更新拍照上传错题
export const updateStudentQuestionApi = (data) => {
  return request.put('/app-api/question/student-question/update', data)
}

// 举一反三推题
export const getSimilarRecommend = (data) => {
  const { questionId: requestQuestionId } = data

  return new Promise(async (resovle) => {
    const res = await request.post('/app-api/question/recommend-question/getSimilarRecommend', data)

    try {
      if (res.data) {
        const q = res.data
        const { questionId } = q
        // 如果题目id和上一题相同，提示没有更多题目
        if (res.data.questionId === requestQuestionId) {
          resovle({
            code: 499,
            data: null,
            msg: '没有更多题目了'
          })
          return
        }

        // 如果不是学科网题目，将题目改为学科网的题目结构
        // 菁优网
        if (q.sourceType && q.sourceType === '3') {
          jywConvertToXkw(q)

          // 题目解析
          const { data: questionSplitRes = [] } = await questionSplitApi([
            {
              questionId: q.questionId,
              stem: q.stem,
              answer: q.answer,
              explanation: q.explanation
            }
          ])

          q.question = {}
          q.question.stem = JSON.parse(
            questionSplitRes[0].stem.replace(
              /<fieldset style=\\\"margin-top:0.1rem;font-size:0.26rem\\\">\\n /,
              '<fieldset style=\\"margin-top:0.1rem;font-size:0.26rem\\">'
            )
          )
          q.question.answer = JSON.parse(questionSplitRes[0].answer)
          q.question.explanation = JSON.parse(questionSplitRes[0].explanation)
        }

        const {
          data: { typeId, typeName }
        } = res

        if (!typeName) {
          const { data } = await getQuestionType({ id: typeId })
          res.data.typeName = data && data.name ? data.name : '未知题型'
        }

        res.data.answerScoreable = getAnswerScoreable({
          stem: res.data.question.stem,
          answer: res.data.question.answer
        })
      }
    } catch (error) {
      console.error(error)
    }

    resovle(res)
  })
}

// 创建错题本
export const createWqBookApi = (data) => {
  return request.post('/app-api/question/wrong-question-book/create', data)
}

// 删除错题本
export const deleteWqBookApi = (id) => {
  return request.delete(`/app-api/question/wrong-question-book/delete?id=${id}`)
}

// 获取题型
export const getQuestionType = (data) => {
  return request.get('/app-api/question/App/type/get', data)
}

// 创建学生使用举一反三使用记录
export const createRecommendUseRecord = (data) => {
  return request.get('/app-api/exam/recommend-use-record/create', data)
}

// 结束学生使用举一反三使用记录
export const exitRecommendUseRecord = (data) => {
  return request.get('/app-api/exam/recommend-use-record/exit', data)
}

// 获取菁优网题目详情
export const getListCompleteByIdsApi = (data) => {
  return request.get('/question-api/question/question/getListCompleteByIds', data)
}
